package cn.bellychang.leetcode.question020;

import java.util.Stack;

/**
 * @author ChangLiang
 * @date 2020/9/7
 */
public class Solution {

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {

            // 异常流程
            if (stack.size() == 0) {
                if (isCloseBracket(c)) {
                    return false;
                }
            }

            // 正常流程
            if (isCloseBracket(c)) {
                // EmptyStackException
                if (!checkIsMatch(stack, c, stack.peek())) {
                    return false;
                }
            } else {
                stack.push(c);
            }
        }
        return stack.size()==0;
    }

    private boolean isCloseBracket(char c) {
        return c == '}' || c == ']' || c == ')';
    }

    private boolean checkIsMatch(Stack stack, Character input, Character peek) {
        if (input == '}' && peek == '{') {
            stack.pop();
            return true;
        }
        if (input == ']' && peek == '[') {
            stack.pop();
            return true;
        }
        if (input == ')' && peek == '(') {
            stack.pop();
            return true;
        }
        return false;
    }
}
